#region

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.SwaggerUI;

#endregion

namespace Leo.Core.Swagger
{
    /// <summary>
    ///     Swagger 配置
    /// </summary>
    public static class SwaggerExtensions
    {
        /// <summary>
        ///     生成配置
        /// </summary>
        /// <param name="options"></param>
        /// <param name="configure"></param>
        public static void BuildGen(this SwaggerGenOptions options, Action<SwaggerGenOptions>? configure = null)
        {
            options.ConfigApiDocument();
            options.ConfigSecurity();
            options.CustomSchemaIds(type => type.FullName);
            options.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["action"]}");
            options.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
            options.IgnoreObsoleteActions();
            options.IgnoreObsoleteProperties();
            //options.HideAbpEndpoints();
            configure?.Invoke(options);
        }

        /// <summary>
        ///     生成UI配置
        /// </summary>
        /// <param name="options"></param>
        /// <param name="app"></param>
        public static void BuildUI(this SwaggerUIOptions options, IApplicationBuilder app)
        {
            //app.UseSwagger(c =>
            //{
            //    c.RouteTemplate = "mycoolapi/swagger/{documentname}/swagger.json";
            //});


            //app.UseSwaggerUI(c =>
            //{
            //    c.SwaggerEndpoint("/mycoolapi/swagger/v1/swagger.json", "My Cool API V1");
            //    c.RoutePrefix = "mycoolapi/swagger";
            //});

            // options.RoutePrefix = "api/swagger";
            // options.InjectJavascript("~/swagger/ui/abp.js");
            // options.InjectJavascript("~/swagger/ui/abp.swagger.js");
            options.DocumentTitle = "接口文档";
            options.DefaultModelsExpandDepth(-1);
            options.DocExpansion(DocExpansion.List);
            if (ApiConfig.GroupList != null)
            {
                ApiConfig.GroupList.ForEach(x =>
                {
                    var groupOpenApiInfo = Helper.GetOpenApiInfo(x) as OpenApiInfo;
                    options.SwaggerEndpoint($"/swagger/{x}/swagger.json", groupOpenApiInfo.Title);
                });
            }
            var configuration = app.ApplicationServices.GetRequiredService<IConfiguration>();
            options.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
            options.OAuthClientSecret(configuration["AuthServer:SwaggerClientSecret"]);
            options.OAuthScopes("Bsjc");
        }
    }
}